package com.jb.web.renderer;

import com.jb.web.application.HtmlConstants;
import com.jb.web.bean.Page;
import com.jb.web.bean.UIComponentImpl;
import com.jb.web.context.WebContext;
import com.jb.web.model.NoVisualComponent;
import com.jb.web.session.SessionUser;

import java.util.Iterator;

import com.jb.faces.component.UIComponent;


/**
 * Default page renderer.
 *
 */
public class PageLayoutManager extends RendererImpl {
    public StringBuffer render(WebContext pCtx, UIComponent itemToRender) {
        Page page = (Page) itemToRender;

        StringBuffer starts = new StringBuffer();
        StringBuffer ends = new StringBuffer();

        StringBuffer children = renderChildren(pCtx, itemToRender);
        
        if (!pCtx.isRunTime())
            pCtx.includeScript(HtmlConstants.DESIGNER);

        if (!page.isEmbedded()) {
            starts = renderBegin(pCtx, itemToRender);
        } else if (pCtx.isRunTime()) {
            starts = renderEmbeddedHeaderChildren(pCtx, itemToRender);
        }

        if (!page.isEmbedded()) {
            ends = renderEnd(pCtx, itemToRender);
            starts.append(pCtx.getPostBodyScript());
        }

        starts.append(children).append(ends);

        if (page.isPersonalizable()) {
            //
            // cache it
            //
        }
        return starts;
    }
    private static String NO_CACHE = "<META HTTP-EQUIV=\"CACHE-CONTROL\" CONTENT=\"NO-CACHE\">\n";
    private static String KEYWORDS = "<META NAME=\"KEYWORDS\" CONTENT=\"";
   
    public StringBuffer renderBegin(WebContext pCtx, UIComponent itemToRender) {
        Page page = (Page) itemToRender;

        StringBuffer stringBuffer = new StringBuffer();
        String pageTitle = evaluate(pCtx, page, page.getTitle());

        stringBuffer.append(HtmlConstants.DOC_TYPE);
        stringBuffer.append("<HTML >\n<HEAD>\n");
        if(!page.isCached()||page.isDialogMode() ) {
            stringBuffer.append(NO_CACHE);
        }
        if(page.getKeyWords()!=null) {
            String keywords = page.getKeyWords();
            keywords = evaluate(pCtx, page, keywords);
            stringBuffer.append(KEYWORDS).append(keywords).append("\">\n");
        }
        stringBuffer.append(HtmlConstants.CONTENT_TYPE).append("<TITLE>").append(pageTitle)
                    .append("</TITLE>\n");

        String pageIcon = page.getIcon();
        if(pageIcon!=null && pageIcon.length()>0) {
             
       //     if(page.isExpression())
            pageIcon = evaluate(pCtx, page, pageIcon);
            
            stringBuffer.append("<link rel=\"shortcut icon\" href=\"")
                .append(pageIcon).append("\" type=\"image/jpg\"/>\n");
        }
        stringBuffer.append(HtmlConstants.getInclude(pCtx));

        if (pCtx.isRunTime()) {
            stringBuffer.append(renderHeaderChildren(pCtx, itemToRender));
        } else if (pCtx.getSession().getSelected() != null) {
            stringBuffer.append("<script language=\"javascript\">\n<!--\n");
            stringBuffer.append("jbDesigner.selectedId = '" + pCtx.getSession().getSelected().getClientId(pCtx) +
                "';");
            stringBuffer.append("\n-->\n</script >\n");
        }
        
        //add droppables
        
        Iterator iter = pCtx.getDroppables().iterator();
        if(iter.hasNext())
        {
            stringBuffer.append("<script language=\"javascript\">\n<!--\n");
            stringBuffer.append("var _JBDroppableCounter=0;");      
            while(iter.hasNext()) {
                String droppable=(String) iter.next();
                stringBuffer.append("JB.droppables[_JBDroppableCounter++] = '" + droppable +"';");      
            }
            stringBuffer.append("\n-->\n</script >\n");
        }
           

        stringBuffer.append("</HEAD>\n");

        if (pCtx.isRunTime()) {
            stringBuffer.append("<BODY ");

            //sets onload handler
            String onLoad = pCtx.getOnLoad();
            stringBuffer.append("onLoad=\"jbLoadPage()\"");

            //renderer page attributes
            stringBuffer.append(addTagProperty("style", page.getStyle(pCtx), null))
                        .append(addTagProperty("class", page.getStyleClass(), null))
                        .append(addTagProperty("droppable", "true", null))
                .append(getEditScript(pCtx, page)).append(">\n");

            //renderer the onload script
            stringBuffer.append("<script language=\"javascript\">\n<!--\n");
            stringBuffer.append("function jbLoadPage(){\n");

            if (onLoad != null) {
                stringBuffer.append(onLoad);
            }
            stringBuffer.append("\n\tJB.initializeRuntime();\n");
            stringBuffer.append("\n}\n-->\n</script >\n");
        } else {
            stringBuffer.append("<BODY onLoad=\"jbDesigner.defaultDesignOnLoad()\"");
            stringBuffer.append(addTagProperty("style", page.getStyle(pCtx), null))
                        .append(addTagProperty("class", page.getStyleClass(), null)).append(getEditScript(pCtx, page))
                        .append(">\n");
        }

        SessionUser userAccount = pCtx.getSession().getUser();
        boolean accessDesign = !page.isReadOnly() && !page.isEmbedded() &&
            userAccount.getId().equals(page.getCreatedBy());

        if (accessDesign) {
            stringBuffer.append("<div id=\"designPad\" class=\"jbDesignPad\" >")
                        .append("<a href=\"javascript:void(0);\" onclick=\"jbDesigner.toggleDesignMode(event, '" +
                page.getId() + ".xsp?editAction=changeMode');return false;\">Design</a>")
                .append(" <a href=\"javascript:void(0);\" onclick=\"jbDesigner.openDesigner(event);return false;\">Open</a>");

            if (userAccount.getAccess() < 1) {
                stringBuffer.append(
                    " <a href=\"javascript:void(0);\" onclick=\"jbDesigner.openConfig(event);return false;\">Config</a>");
            }
         
            stringBuffer.append(
                " <a href=\"javascript:void(0);\" onclick=\"jbDesigner.toggleDebug(event);return false;\">Debug</a>");
            
            stringBuffer.append("</div>");
        }

        return stringBuffer;
    }

    public StringBuffer renderChildren(WebContext pCtx, UIComponent itemToRender) {
        StringBuffer stringBuffer = new StringBuffer();
        Page page = (Page) itemToRender;

        //this must be after toolbar, or ie can not render it must be a bug in menu.js
        String pageAlign = page.getAlign();
        if (pageAlign!=null && pageAlign.length()>0) {
            stringBuffer.append("<"+pageAlign+">");
        }

        String id = pCtx.getSession().getUser().getId();

        if (!page.isEmbedded() && !pCtx.isRunTime() && !page.isDialogMode() && page.isDesignable()) {
            Page toolBar = pCtx.getToolBar();
            if ((toolBar != null) && "true".equalsIgnoreCase(toolBar.getVisible()) && id.equals(page.getCreatedBy())) {
                toolBar.setRendererType("com.jb.web.bean.inspector.renderer.ToolPageRenderer");
                stringBuffer.append(toolBar.render(pCtx));
            }
        }

        //list children sorted by sequence number    
        Iterator iter = page.getChildrenSorted(null).iterator();

        if (!iter.hasNext()) { //empty page
            stringBuffer.append(pCtx.getResource("jb.page.add.components"));
        }

        if (!pCtx.isRunTime()) {
            stringBuffer.append(renderHeaderChildren(pCtx, itemToRender));
        }

        while (iter.hasNext()) {
            UIComponentImpl child = (UIComponentImpl) iter.next();
            if (isVisible(pCtx, child) && !(child instanceof NoVisualComponent)) {
                stringBuffer.append(child.render(pCtx));
            }
        }

        return stringBuffer;
    }

    private StringBuffer renderEmbeddedHeaderChildren(WebContext pCtx, UIComponent itemToRender) {
        StringBuffer stringBuffer = new StringBuffer();
        Page page = (Page) itemToRender;

        //renders variables
        Iterator variables = page.getChildrenByType(NoVisualComponent.class).iterator();

        if (variables.hasNext()) {
            while (variables.hasNext()) {
                UIComponentImpl child = (UIComponentImpl) variables.next();

                stringBuffer.append(child.render(pCtx));
            }
        }

        return stringBuffer;
    }

    public StringBuffer renderEnd(WebContext pCtx, UIComponent itemToRender) {
        Page page = (Page) itemToRender;

        StringBuffer stringBuffer = new StringBuffer();
        String pageAlign = page.getAlign();
        if (pageAlign!=null && pageAlign.length()>0) {
            stringBuffer.append("</"+pageAlign+">");
        }

        stringBuffer.append("</BODY></HTML>");

        return stringBuffer;
    }

    private StringBuffer renderHeaderChildren(WebContext pCtx, UIComponent itemToRender) {
        StringBuffer stringBuffer = new StringBuffer();
        Page page = (Page) itemToRender;

        //renders variables
        Iterator variables = page.getChildrenByType(NoVisualComponent.class).iterator();

        if (variables.hasNext()) {
            boolean designMode = !pCtx.isRunTime() && page.isDesignable() && !page.isDialogMode();
            //wrap a absolute div jbVariableBox
            if (designMode) {
                /*
                 * div box class=jbVariableBox
                 *  head div
                 *      span caption  span toggle view onclick to hide details
                 *  table for all the variables
                 */
                stringBuffer.append("<div id=\"jbVariableBox\"");

                if (pCtx.getSession().isDraggable()) {
                    stringBuffer.append(" draggable=\"true\" ");
                }

                if (pCtx.getSession().isShowManagedBean()) {
                    stringBuffer.append(" >");
                } else {
                    stringBuffer.append(" style=\"display:none\" >");
                }

                stringBuffer.append("<div ><span style=\"float:left;\" >").append(pCtx.getResource("jb.variables"))
                            .append("</span>")
                            .append("<span style=\"float:right;width:8px;background-color:silver;cursor:default;\" ")
                            .append("onclick=\"jbDesigner.toggleMBBox(event, '" + page.getClientId() +
                    "');return false;\">").append("&nbsp;</span></div><br><table id=\"variableTable\" >");
            }

            while (variables.hasNext()) {
                UIComponentImpl child = (UIComponentImpl) variables.next();

                if (designMode) {
                    stringBuffer.append("<tr><td align=\"left\">");
                }

                stringBuffer.append(child.render(pCtx));

                if (designMode) {
                    stringBuffer.append("</td></tr>");
                }
            }

            if (designMode) {
                stringBuffer.append("</table></div>");
            }
        }

        return stringBuffer;
    }
}
